package com.block.channel.flow.channel;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.channel.flow.IChannelReportService;
import com.block.channel.model.result.ReprotFlowResult;
import com.block.common.bean.CommonParam;
import com.block.common.constant.RedisKeyConstant;
import com.block.common.service.LogFactory;
import com.block.db.entity.ChannelActionMonitorRecord;
import com.block.db.entity.ChannelBaseInfo;
import com.block.db.mapper.ChannelActionMonitorRecordMapper;
import org.apache.http.Consts;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class HuaWeiChannelReportService implements IChannelReportService {

    private static Logger log = LogFactory.getCommLog();

    private String getTokenUrl = "https://connect-api.cloud.huawei.com/api/oauth2/v1/token";
    private String requestUrl = "https://connect-api.cloud.huawei.com/api/datasource/v1/track/activate";

    // token
    private String clientId = "1451534564252980160";
    private String clientSecret = "EDC194B19D8B62908FAB62E078C45C0970B310174A6D768D823B275072379871";

    //

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Resource
    ChannelActionMonitorRecordMapper channelActionMonitorRecordMapper;

    @Override
    public ReprotFlowResult registerActionReport(CommonParam commonParam, ChannelBaseInfo channelBaseInfo) {

        ReprotFlowResult flowResult = new ReprotFlowResult();
        flowResult.setSuccess(false);

        JSONObject headObject = commonParam.getHeadObject();

        String OAID = headObject.getString("originparm1");
        String IMEI_MD5 = headObject.getString("originparm2");

        if (StrUtil.isEmpty(OAID) && StrUtil.isEmpty(IMEI_MD5)){
            flowResult.setCode("-2");
            flowResult.setMessage("OAID和IMEI_MD5参数为空，不做处理");
            return flowResult;
        }

        // 根据 OAID 和 IMEI_MD5 查询 监测数据
//        List<ChannelActionMonitorRecord> monitorRecordList = channelActionMonitorRecordMapper.queryListByOaid(OAID);

//        if (CollUtil.isEmpty(monitorRecordList)){
//            flowResult.setCode("-2");
//            flowResult.setMessage("可上报列表为空");
//            return flowResult;
//        }

        String  token = this.getToken();
        if (StrUtil.isEmpty(token)){
            flowResult.setCode("-2");
            flowResult.setMessage("获取token为空");
            return flowResult;
        }

        ChannelActionMonitorRecord monitorRecord = channelActionMonitorRecordMapper.queryEntityByUnikeyAndActionType(OAID, "INSTALL", channelBaseInfo.getChannelCode());
        if (ObjectUtil.isEmpty(monitorRecord)){
            flowResult.setCode("-2");
            flowResult.setMessage("可上报列表为空");
            return flowResult;
        }

//        for (ChannelActionMonitorRecord monitorRecord : monitorRecordList) {

            Map<String, Object> bizMap = new HashMap<>();
            bizMap.put("appId", "110687801");

            bizMap.put("deviceIdType", "OAID");
            bizMap.put("deviceId", monitorRecord.getUniqueKey());

            long actionTime = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli();
            bizMap.put("actionTime", actionTime);
            bizMap.put("actionType", "7");

            // 需要查询表信息
            bizMap.put("callBack",  monitorRecord.getCallbackInfo());

            StringEntity entity = new StringEntity(JSON.toJSONString(bizMap), Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");

            String authorization = StrUtil.format("Bearer {}", token);

            log.info("【华为应用市场上报】【注册】【开始请求】【reqestUrl】{}【clientId】{}【authorization】{}【bizMap】{}", requestUrl, clientId, authorization, JSON.toJSONString(bizMap));

            try {

                HttpPost httpPost = new HttpPost(requestUrl);
                httpPost.setEntity(entity);
                httpPost.setHeader("client_id", clientId);
                httpPost.setHeader("Authorization", authorization);

                CloseableHttpClient httpClient = HttpClients.createDefault();
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                int statusCode = httpResponse.getStatusLine().getStatusCode();

                log.info("【华为应用市场上报】【注册】【请求结束】【statusCode】{}",  statusCode);
                if (statusCode == HttpStatus.SC_OK) {
                    BufferedReader br =
                            new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), Consts.UTF_8));
                    String result = br.readLine();

                    log.info("【华为应用市场上报】【注册】【请求结束】【result】{}",  result);

                    JSONObject jsonObject = JSON.parseObject(result);
                    Integer code = jsonObject.getInteger("code");

                    ChannelActionMonitorRecord updateEntity =new ChannelActionMonitorRecord();
                    updateEntity.setId(monitorRecord.getId());
                    updateEntity.setResultInfo(result);
                    if (ObjectUtil.equals(code, Integer.valueOf(0))){
                        updateEntity.setStatus("1");
                    }else{
                        updateEntity.setStatus(code+"");
                    }
                    int i = channelActionMonitorRecordMapper.updateById(updateEntity);

                }

                httpPost.releaseConnection();
                httpClient.close();

                flowResult.setSuccess(true);
                flowResult.setMessage("处理数据："+monitorRecord.getId());

            }catch (Exception exception){
                exception.printStackTrace();
                flowResult.setSuccess(false);
                flowResult.setMessage("处理数据异常：");

            }
//        }

        return flowResult;
    }
    @Override
    public ReprotFlowResult sourceActionReport(CommonParam commonParam, ChannelBaseInfo channelBaseInfo) {
        return null;
    }
    @Override
    public ReprotFlowResult downloadActionReport(CommonParam commonParam, ChannelBaseInfo channelBaseInfo) {
        return null;
    }

    @Override
    public ReprotFlowResult payBuyActionReport(CommonParam commonParam, ChannelBaseInfo channelBaseInfo) {
        return null;
    }


    public String getToken(){

        try {

            String redisKey = StrUtil.format(RedisKeyConstant.HUAWEI_CHANNEL_API_TOKEN, clientId);
            String token = stringRedisTemplate.opsForValue().get(redisKey);
            if (StrUtil.isNotEmpty(token)){
                return token;
            }

            JSONObject keyString = new JSONObject();
            keyString.put("client_id", clientId);
            keyString.put("client_secret", clientSecret);
            keyString.put("grant_type", "client_credentials");

            StringEntity entity = new StringEntity(keyString.toString(), Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");

            log.info("【华为应用市场上报】【获取token】【开始请求】【reqestUrl】{}【bizMap】{}", getTokenUrl, JSON.toJSONString(keyString));

            HttpPost httpPost = new HttpPost(getTokenUrl);
            httpPost.setEntity(entity);

            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();

            String accessToken = "";
            if (statusCode == HttpStatus.SC_OK) {
                BufferedReader br =
                        new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), Consts.UTF_8));
                String result = br.readLine();

                log.info("【华为应用市场上报】【获取token】【请求结束】【result】{}", result);

                JSONObject resultObject = JSONObject.parseObject(result);
                accessToken = resultObject.getString("access_token");
                Long expiresIn = resultObject.getLong("expires_in");

                Long expiresInReal = expiresIn - 180;
                stringRedisTemplate.opsForValue().set(redisKey, accessToken, expiresInReal, TimeUnit.SECONDS);
            }

            httpPost.releaseConnection();
            httpClient.close();

            return accessToken;
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return "";
    }


}
